#include "VHistorySession.h"
#include "ui_VHistorySession.h"
#include <QDebug>
#include <QMenu>
#include <QDateTime>
#include "CMainWindow.h"
#include "CUIHelper.h"
#include "CHelper.h"
#include "CTableSession.h"

VHistorySession::VHistorySession(const StSession &sessionInfo, QWidget *parent) :
    QFrame(parent),
    ui(new Ui::VHistorySession),
    m_strId(sessionInfo.id)
{
    ui->setupUi(this);

    QMenu *pMenu = new QMenu(this);
    QAction *pActionDel = pMenu->addAction(tr("删除"));
    connect(pActionDel,&QAction::triggered,[=]{
        qInfo()<<"删除会话:"<<sessionInfo.id<<"信息!";
        CTableSession::instance()->deleteRow(sessionInfo.id);
        this->deleteLater();
    });
    CUIHelper::menuResetStyle(pMenu);

    ui->pushButton_menu->setText(QChar(0xe689));
    ui->pushButton_menu->setProperty("iconText",true);
    connect(ui->pushButton_menu,&QPushButton::clicked,[=]{
        pMenu->exec(ui->pushButton_menu->mapToGlobal(QPoint(0,ui->pushButton_menu->height())));
    });

    //显示会话信息
    ui->label_title->setText(sessionInfo.name);

    //@BUG 关闭的会话 sessionData未打开
    if(!sessionInfo.session_type.isEmpty())
    {
        ui->label_protocal->setText(sessionInfo.session_type);
        if("Serial" == sessionInfo.session_type){
            ui->label_info_1->setText(sessionInfo.seial_name);
            ui->label_info_2->setText(QString("%1 %2 %3")
                                      .arg(sessionInfo.baude)
                                      .arg(sessionInfo.data_bit)
                                      .arg(sessionInfo.stop_bit));
        }else{
            ui->label_info_1->setText(sessionInfo.ip);
            ui->label_info_2->setText(QString::number(sessionInfo.port));
        }
    }else{
        ui->label_protocal->setText(tr("未知"));
        ui->label_info_1->setText(tr("未知"));
        ui->label_info_2->setText(tr("未知"));
    }

    QString strDiffHuman = diffHuman(CHelper::dateTime(sessionInfo.close_time));

    ui->label_time->setText(strDiffHuman);
    this->setToolTip(sessionInfo.close_time);
}

VHistorySession::~VHistorySession()
{
    delete ui;
}

QString VHistorySession::diffHuman(QDateTime dt)
{
    int nDays = dt.daysTo(QDateTime::currentDateTime());
    QString strText;

    //小于一分钟
    if(nDays < 1)
    {
        strText = dt.toString("hh:mm");
    }
    //一周内 显示周几
    else if(nDays < 7)
    {
        QString strArr[] = {tr("周一"),tr("周二"),tr("周三"),tr("周四"),
                            tr("周五"),tr("周六"),tr("周日")};
        int nWeekDay = dt.date().dayOfWeek();
        strText = strArr[nWeekDay - 1];
    }
    //一年内 显示mm/dd
    else if(nDays < 365)
    {
        strText = dt.toString("MM/dd");
    }
    else
    {
        strText = dt.toString("yyyy/MM/dd");
    }

    return strText;
}

void VHistorySession::mousePressEvent(QMouseEvent *event)
{
    qDebug()<<"打开会话:"<<m_strId;

    CMainWindow::getInstance()->hSplitSession(m_strId);
}
